<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
      layout:decorate="~{manage/layout}" lang="zh">
<head>
    <title>组织管理</title>
    <style rel="stylesheet">
        .organize-tree {
            float: left;
        }

        .organize-operator-container {
            height: 56px;
            display: flex;
            align-items: center;
            margin-top: 16px;
        }

        .organize-operator-container .btn-container {
            display: flex;
            justify-content: space-between;
        }

        .mdc-tree {
            margin-top: 16px
        }

        .data-table {
            width: calc(100% - 300px);
            margin-left: 16px;
        }

        .mdc-data-table__container.fixed-width {
            width: 100%;
        }

    </style>
</head>
<body>
<div layout:fragment="main-container" class="main-container">
    <div class="organize-tree">
        <h2>组织管理</h2>
        <div class="organize-operator-container">
            <div class="btn-container">
                <button class="mdc-button mdc-button--raised" id="refreshBtnOrg">
                    <span class="mdc-button__label">刷新</span>
                </button>
                <a class="mdc-button mdc-button--raised" id="addBtnOrg" data-href="/manage/organize"
                   sec:authorize="hasAnyAuthority('global:create','organize:create')">
                    <span class="mdc-button__label">添加</span>
                </a>
                <button class="mdc-button mdc-button--raised" id="editBtnOrg" disabled
                        sec:authorize="hasAnyAuthority('global:write','organize:write')">
                    <span class="mdc-button__label">编辑</span>
                </button>
                <button class="mdc-button mdc-button--raised" id="delBtnOrg" disabled
                        sec:authorize="hasAnyAuthority('global:delete','organize:delete')">
                    <span class="mdc-button__label">删除</span>
                </button>
            </div>
        </div>
        <div id="mdcTree" class="mdc-tree"></div>
    </div>
    <div id="mdc-data-table" class="mdc-data-table__container mdc-float__left data-table mdc-non-display">
        <h2 id="title">岗位成员管理</h2>
        <!--扩展搜索条件-->
        <!--        <div class="search-container-extend">-->
        <!--        </div>-->
        <div class="operator-container">
            <div class="btn-container">
                <button class="mdc-button mdc-button--raised" id="refreshBtn">
                    <span class="mdc-button__label">刷新</span>
                </button>
                <a class="mdc-button mdc-button--raised" id="addBtn" disabled
                   data-href="/manage/organize/member?organizeId={}"
                   sec:authorize="hasAnyAuthority('global:create','post:create')">
                    <span class="mdc-button__label">添加</span>
                </a>
                <button class="mdc-button mdc-button--raised" id="editBtn" disabled
                        sec:authorize="hasAnyAuthority('global:write','post:write')">
                    <span class="mdc-button__label">编辑</span>
                </button>
                <button class="mdc-button mdc-button--raised" id="delBtn" disabled
                        sec:authorize="hasAnyAuthority('global:delete','post:delete')">
                    <span class="mdc-button__label">删除</span>
                </button>
            </div>
            <div class="search-container">
                <div class="mdc-text-field text-field mdc-text-field--fullwidth mdc-text-field--no-label mdc-ripple-upgraded mdc-text-field--with-trailing-icon"
                     data-mdc-auto-init="MDCTextField">
                    <input type="text" id="criteria" class="mdc-text-field__input"
                           placeholder="请输入名称" autocomplete="off" data-enter-trigger="refreshTable">
                    <i class="material-icons mdc-text-field__icon" tabindex="0" role="button" id="searchBtn">search</i>
                    <div class="mdc-line-ripple"></div>
                </div>
            </div>
        </div>
    </div>
    <div th:fragment="editContainerOrg" id="editContainerOrg"></div>
    <div th:fragment="editContainer" id="editContainer"></div>

    <!-- 选择成员弹窗 -->
    <div id="pop-table-container" class="mdc-non-display">
        <div id="selectMemberTable" class="mdc-data-table__container mdc-float__left fixed-width">
            <div class="operator-container">
                <div class="btn-container"></div>
                <div class="search-container">
                    <div class="mdc-text-field text-field mdc-text-field--fullwidth mdc-text-field--no-label mdc-ripple-upgraded mdc-text-field--with-trailing-icon"
                         data-mdc-auto-init="MDCTextField">
                        <input type="text" id="criteriaMember" class="mdc-text-field__input"
                               placeholder="请输入工号 | 名称 | 电话" autocomplete="off" data-enter-trigger="refreshTableMember">
                        <i class="material-icons mdc-text-field__icon" tabindex="0" role="button"
                           id="searchBtnMember">search</i>
                        <div class="mdc-line-ripple"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<th:block layout:fragment="script">
    <script type="text/javascript" th:inline="javascript">
      $(function() {
        console.log(' organizes: ', [[${organizes}]]);
        let organizeId;
        let initTable = 0;
        let mdcTree = $('#mdcTree').mdcTree({
          data: [[${organizes}]],
          id: 'id',
          parentId: 'prevId',
          label: 'name',
          icon: 'icon',
          expandAll: false,
          checkbox: false,
          toggleEvt: function(cell) {
            let selectItemId = cell.dataset.id;
            console.log(' 点击元素: ', selectItemId, organizeId);
            // 表格初始化,这里
            let $mdcDataTable = $('#mdc-data-table');
            !initTable++ ? window.mdcDataTable = $mdcDataTable.mdcDataTable({
                  url: '/manage/organize/member/page',
                  queryParams: {'organizeId': selectItemId},
                  container: '#mdc-data-table',
                  columns: [
                    {
                      data: 'name',
                    },
                    {
                      data: 'postName',
                    },
                  ],
                  thead: [
                    {
                      data: '名称',
                      style: 'mdc-data-table__cell--non-numeric',
                    },
                    {
                      data: '岗位',
                      style: 'mdc-data-table__cell--non-numeric',
                    },
                  ],
                  // 是否分页,暂不支持
                  pagination: true,
                  // 页面数据条数,暂不支持
                  pageSize: 5,
                  // 设置页面可以显示的数据条数,暂不支持
                  pageList: [5, 10, 15, 20],
                  // 首页页码
                  pageNumber: 1,
                  editable: false,
                  callback: function() {
                  },
                  noneSelect: function() {
                    $('#editBtn').prop('disabled', true);
                    $('#delBtn').prop('disabled', true);
                    $('#roleBtn').prop('disabled', true);
                    $('#menuBtn').prop('disabled', true);
                    $('#privilegeBtn').prop('disabled', true);
                  },
                  singleSelect: function() {
                    $('#editBtn').prop('disabled', false);
                    $('#delBtn').prop('disabled', false);
                    $('#roleBtn').prop('disabled', false);
                    $('#menuBtn').prop('disabled', false);
                    $('#privilegeBtn').prop('disabled', false);
                  },
                  multipleSelect: function() {
                    $('#editBtn').prop('disabled', true);
                    $('#delBtn').prop('disabled', false);
                    $('#roleBtn').prop('disabled', true);
                    $('#menuBtn').prop('disabled', true);
                    $('#privilegeBtn').prop('disabled', true);
                  },
                })
                : (organizeId === selectItemId ? function() {
                } : window.mdcDataTable.refresh(
                {'organizeId': selectItemId, criteria: $('#criteria').val()}));
            organizeId = selectItemId;
            $('#title').text($(cell).text() + '成员管理');
            $mdcDataTable.show(0);
            // 组织树编辑/删除操作可用
            $('#editBtnOrg').prop('disabled', false);
            $('#delBtnOrg').prop('disabled', false);
            // 获取当前组织的岗位,如果已配置(存在)岗位,人员添加可用
            $.get($.strFormat('/manage/post/page?organizeId={}', organizeId), {}, function(res) {
              console.log($.strFormat(' organize: {},post: {},{}', organizeId, JSON.stringify(res),
                  res.data.totalElements > 0));
              let $addBtn = $('#addBtn');
              res.data.totalElements > 0 ? $addBtn.attr('disabled', false)
                  : $addBtn.attr('disabled', true);
            });
          },
        });

        // 组织刷新
        $('#refreshBtnOrg').on('click', refreshOrganize);

        // 组织树刷新
        function refreshOrganize() {
          $.get('/manage/organize/page', {page: -1, size: -1}, function(res) {
            res.result === true ? mdcTree.refresh({data: res.data.content}) : $.alert(res.msg);
          });
        }

        // 组织添加
        $('#addBtnOrg').on('click', function() {
          console.log(organizeId);
          // if ($.isNegativeNum(organizeId)) {
          //   $.alert('请选择左侧组织');
          //   return false;
          // }
          $('#editContainerOrg').load(this.dataset.href + '?prevId=' + organizeId, () => editOrganize());
          return false;
        });

        // 编辑组织
        $('#editBtnOrg').on('click', function() {
          console.log(organizeId);
          if ($.isNegativeNum(organizeId)) {
            $.alert('请选择一条记录');
            return false;
          }
          $('#editContainerOrg').load('/manage/organize/' + organizeId, () => editOrganize(1));
          return false;
        });

        // 删除组织
        $('#delBtnOrg').on('click', function() {
          if ($.isNegativeNum(organizeId)) {
            $.alert('请选择一条记录');
            return false;
          }
          $.confirm('确认要删除这一条记录么 ?', function() {
            $.delete('/manage/organize/deleteBatch', {'ids': organizeId}, function(res) {
              console.log(JSON.stringify(res));
              $.alert(res.msg);
              refreshOrganize();
            }, function(res) {
              console.log(JSON.stringify(res));
              $.alert(res.msg);
            });
          });
        });

        window.refreshTable = function(delCount = 0) {
          window.mdcDataTable.refresh({'organizeId': organizeId, criteria: $('#criteria').val()}, delCount);
          $('#editBtn').prop('disabled', true);
          $('#delBtn').prop('disabled', true);
          $('#roleBtn').prop('disabled', true);
          $('#menuBtn').prop('disabled', true);
          $('#privilegeBtn').prop('disabled', true);
        };

        // 刷新,搜索
        $('#refreshBtn,#searchBtn').on('click', refreshTable);

        // 添加
        $('#addBtn').on('click', function() {
          console.log(organizeId);
          if ($.isNegativeNum(organizeId)) {
            $.alert('请选择左侧组织');
            return false;
          }
          $('#editContainer').load($.strFormat(this.dataset.href, organizeId), () => edit());
          return false;
        });

        // 编辑
        $('#editBtn').on('click', function() {
          console.log(organizeId);
          if ($.isNegativeNum(organizeId)) {
            $.alert('请选择左侧组织');
            return false;
          }
          let selectItems = window.mdcDataTable.getSelectItems();
          if (selectItems.length !== 1) {
            $.alert('请选择一条记录');
            return false;
          }
          $('#editContainer').load('/manage/organize/member/' + selectItems[0].id, () => edit(1));
          return false;
        });

        // TODO-WARN: 已知BUG: 每次弹窗初始化mdc-select组件,导致body会无限拼接下拉元素
        // TODO-WARN: 体验优化: 保存失败时,不应该关闭弹窗 [修复滞后]

        // 新增/更新组织
        function editOrganize(type = 0) {
          let thisNode = $('#editContainerOrg');
          let html = $(thisNode).html();
          $(thisNode).empty();
          $(thisNode).hide();
          $.modal({
            'title': (type === 0 ? '添加' : '编辑') + '组织',
            'content': html,
            'titleAlign': 'center',
            'openedCallback': function(data) {
              console.debug(' 打开回调log: ', data);
              $(data.target).initMDCTextField();
              $(data.target).initMDCSelect();
            },
          }, function(dom) {
            let $form = $(dom.target).find('#form');
            let data = {};
            $form.serializeArray().forEach(function(item) {
              data[item.name] = item.value;
            });
            let selects = $('.mdc-select input[name]');
            for (let i = 0; i < selects.length; i++) {
              let $input = $(selects[i]);
              let value = $input.val();
              let validTip = $input.attr('data-validtip');
              if ($input.prop('required') && (!value || Number(value) < 0)) {
                $.alert(validTip, function() {
                  $input.siblings('.mdc-select__selected-text').trigger('click');
                });
                return false;
              }
            }

            let textFields = document.querySelectorAll('.mdc-text-field');
            for (let i = 0; i < textFields.length; i++) {
              console.log(i, textFields[i]);
              let $input = $(new mdc.textField.MDCTextField(textFields[i]).input_);
              let value = $input.val();
              let required = Boolean($input.prop('required'));
              let minLength = $input.attr('minlength');
              let maxLength = $input.attr('maxlength');
              let validTip = $input.attr('data-validtip');
              let pattern = $input.attr('data-pattern');
              if (!$.valid(value, !required, minLength, maxLength, validTip || '参数校验失败', pattern)) {
                $input.trigger('focus');
                return false;
              }
            }
            data.prevId = $('input[name=prevId]').val();
            console.log(JSON.stringify(data));
            let id = $(dom.target).find('input[name=id]').val();
            console.log(' log: id = ', id);
            id > 0 ?
                $.put('/manage/organize/' + id, data, function(res) {
                  res.result === true ? $.alert(res.msg, refreshOrganize) : $.alert(res.msg);
                }) : $.post('/manage/organize', data, function(res) {
                  res.result === true ? $.alert(res.msg, refreshOrganize) : $.alert(res.msg);
                });
          });
        }

        // 新增/更新组织成员
        function edit(type = 0) {
          let thisNode = $('#editContainer');
          let html = $(thisNode).html();
          $(thisNode).empty();
          $(thisNode).hide();
          $.modal({
            'title': (type === 0 ? '添加' : '修改') + '组织人员',
            'content': html,
            'titleAlign': 'center',
            'openedCallback': function(data) {
              console.debug(' 打开回调log: ', data);
              $(data.target).initMDCTextField();
              $(data.target).initMDCSelect();
            },
          }, function(dom) {
            let selects = $('.mdc-select input[name]');
            for (let i = 0; i < selects.length; i++) {
              let $input = $(selects[i]);
              if ($.isNegativeNum($input.val())) {
                $.alert($input.attr('data-validtip'), function() {
                  $input.siblings('.mdc-select__selected-text').trigger('click');
                });
                return false;
              }
            }
            let data = {};
            let textFields = document.querySelectorAll('.mdc-text-field');
            for (let i = 0; i < textFields.length; i++) {
              console.log(i, textFields[i]);
              let $input = $(new mdc.textField.MDCTextField(textFields[i]).input_);
              let value = $input.val();
              let required = Boolean($input.prop('required'));
              let minLength = $input.attr('minlength');
              let maxLength = $input.attr('maxlength');
              let validTip = $input.attr('data-validtip');
              let pattern = $input.attr('data-pattern');
              if (!$.valid(value, !required, minLength, maxLength, validTip || '参数校验失败', pattern)) {
                $input.trigger('focus');
                return false;
              }
            }
            data.organizeId = $('input[name=organizeId]').val();
            let memberIds = $('#memberIds').attr('data-value').split(',');
            if (!memberIds.find(item => $.isPositiveNum(item))) {
              $.alert('请选择成员');
              return false;
            }
            data.memberIds = memberIds.toString();
            data.postId = $('input[name=postId]').val();
            console.log(JSON.stringify(data));
            let id = $(dom.target).find('input[name=id]').val();
            console.log(' log: id = ', id);
            id > 0 ?
                $.put('/manage/organize/member/' + id, data, function(res) {
                  res.result === true ? $.alert(res.msg, function() {
                    window.refreshTable();
                  }) : $.alert(res.msg);
                }) : $.post('/manage/organize/member', data, function(res) {
                  res.result === true ? $.alert(res.msg, function() {
                    window.refreshTable();
                  }) : $.alert(res.msg);
                });
          });
        }

        // 删除
        $('#delBtn').on('click', function() {
          let selectItems = window.mdcDataTable.getSelectItems();
          let delCount = selectItems.length;
          if (delCount < 1) {
            $.alert('请至少选择一条记录');
            return false;
          }
          $.confirm('确认要删除这' + delCount + '条记录么 ?', function() {
            let ids = [];
            selectItems.forEach(function(item) {
              ids.push(item.id);
            });
            $.delete('/manage/post/deleteBatch', {'ids': ids.toString()}, function(res) {
              console.log(JSON.stringify(res));
              $.alert(res.msg);
              window.refreshTable(delCount);
            }, function(res) {
              console.log(JSON.stringify(res));
              $.alert(res.msg);
            });
          });
        });

        // 选择成员事件

        // 添加/编辑成员
        // 选择成员弹窗
        $('body').on('click', '#selectMember', function() {
          if (window.mdcDataTableMember) {
            // 重置表格信息
            $('#criteriaMember').val('');
            window.mdcDataTableMember.refresh({page: 1}, 0);
            $.modal({
              title: '请选择成员',
              content: $('#selectMemberTable'),
              width: 800,
              contentType: 2,
              openedCallback: function() {
                window.mdcDataTable.fixBtnColor();
              },
            }, function(data, container) {
              let selectItems = window.mdcDataTableMember.getSelectItems();
              if (selectItems.length < 1) {
                $.alert({'title': '警告', 'content': '请选择成员'});
                return false;
              }
              let selectIds = selectItems.map(item => item['id']);
              let selectNames = selectItems.map(item => item['name']);
              setTimeout(function() {
                $('#pop-table-container').append($('#selectMemberTable'));
              }, 100);
              let $member = $('#memberIds');
              $member.val(selectNames);
              $member.attr('data-value', selectIds);
              console.log($.strFormat(' 选择员工: {},{}', JSON.stringify(selectIds), container));
              // 刷新文本框,具体是浮动label
              new mdc.textField.MDCTextField($member.parent('.mdc-text-field').get(0));
            }, function() {
              setTimeout(function() {
                $('#pop-table-container').append($('#selectMemberTable'));
              }, 100);
            });
          } else {
            window.mdcDataTableMember = $('#selectMemberTable').mdcDataTable({
              url: '/manage/organize/member/pageDetach',
              queryParams: {},
              externalStyle: 'fixed-width',
              container: '#selectMemberTable',
              columns: [
                {
                  data: 'empNo',
                },
                {
                  data: 'name',
                },
                {
                  data: 'genderDesc',
                },
                {
                  data: 'phone',
                },
              ],
              thead: [
                {
                  data: '工号',
                  style: 'mdc-data-table__cell--non-numeric',
                },
                {
                  data: '姓名',
                  style: 'mdc-data-table__cell--non-numeric',
                },
                {
                  data: '性别',
                  style: 'mdc-data-table__cell--non-numeric',
                },
                {
                  data: '电话',
                  style: 'mdc-data-table__cell--non-numeric',
                },
              ],
              check: true,
              // 是否分页
              pagination: true,
              // 页面数据条数
              pageSize: 2,
              // 设置页面可以显示的数据条数
              pageList: [5, 10, 15, 20],
              // 首页页码
              pageNumber: 1,
              editable: false,
              onInitFinish: function() {
                $.modal({
                  title: '请选择成员',
                  content: $('#selectMemberTable'),
                  shadeClose: false,
                  width: 800,
                  contentType: 2,
                  openedCallback: function(data) {
                    window.mdcDataTable.fixBtnColor();
                  },
                }, function() {
                  // 可能需要支持选择多个成员
                  let selectItems = window.mdcDataTableMember.getSelectItems();
                  if (selectItems.length < 1) {
                    $.alert({'title': '警告', 'content': '请选择成员'});
                    return false;
                  }
                  let selectIds = selectItems.map(item => item['id']);
                  let selectNames = selectItems.map(item => item['name']);
                  setTimeout(function() {
                    $('#pop-table-container').append($('#selectMemberTable'));
                  }, 100);
                  let $member = $('#memberIds');
                  $member.val(selectNames);
                  $member.attr('data-value', selectIds);
                  console.log($.strFormat(' 选择员工: {}', JSON.stringify(selectIds)));
                  // 刷新文本框,具体是浮动label
                  new mdc.textField.MDCTextField($member.parent('.mdc-text-field').get(0));
                }, function() {
                  setTimeout(function() {
                    $('#pop-table-container').append($('#selectMemberTable'));
                  }, 100);
                });
              },
              rowClick: function(row, data, index, rowNode) {
                console.log($.strFormat('{},{}', JSON.stringify(row), index));
                // 选中当前行
                new mdc.checkbox.MDCCheckbox(
                    $(rowNode).find('td:first-of-type div.mdc-checkbox').get(0)).checked = true;
                $(rowNode).addClass('is-selected');
                $('#selectMemberTable').
                parents('.mdc-dialog__surface').
                find('button[data-mdc-dialog-action="yes"]').
                trigger('click');
              },
            });
          }
          return false;
        });

        window.refreshTableMember = function(delCount = 0) {
          window.mdcDataTableMember.refresh({criteria: $('#criteriaMember').val()}, delCount);
        };

        // 刷新,搜索
        $('#searchBtnMember').on('click', refreshTableMember);

        // 提交表单
        $('#editBtnMember').on('click', function() {
          let $form = $('#form');
          let data = {};
          $form.serializeArray().forEach(function(item) {
            debugger
            item.name === 'memberIds' ? data[item.name] = item.attr('data-value') : data[item.name] = item.value;
          });
          let selects = $('.mdc-select input[name]');
          for (let i = 0; i < selects.length; i++) {
            let $input = $(selects[i]);
            let value = $input.val();
            let validTip = $input.attr('data-validtip');
            if (!value || Number(value) < 0) {
              $.alert(validTip, function() {
                $input.siblings('.mdc-select__selected-text').trigger('click');
              });
              return false;
            }
          }

          let textFields = document.querySelectorAll('.mdc-text-field');
          for (let i = 0; i < textFields.length; i++) {
            console.log(i, textFields[i]);
            let $input = $(new mdc.textField.MDCTextField(textFields[i]).input_);
            let value = $input.val();
            let required = Boolean($input.prop('required'));
            let minLength = $input.attr('minlength');
            let maxLength = $input.attr('maxlength');
            let validTip = $input.attr('data-validtip');
            let pattern = $input.attr('data-pattern');
            if (!$.valid(value, !required, minLength, maxLength, validTip || '参数校验失败', pattern)) {
              $input.focus();
              return false;
            }
          }
          data.organizeId = $('input[name=organizeId]').val();
          console.log(JSON.stringify(data));
          id > 0 ?
              $.put('/manage/organize/member/' + id, data, function(res) {
                res.result === true ? $.alert(res.msg, function() {
                  window.location.href = '/manage/post/index';
                }) : $.alert(res.msg);
              }) : $.post('/manage/organize/member', data, function(res) {
                res.result === true ? $.alert(res.msg, function() {
                  window.location.href = '/manage/organize/member/index';
                }) : $.alert(res.msg);
              });
          return false;
        });
        // 选择成员事件
      });
    </script>
</th:block>
</body>
</html>
